<template>
  <view class="filter-list-view bg-white padding" v-if="tabs.length > 0 &&  Object.keys(formModel).length > 0 ">
    <uni-forms ref="form" :label-width="showLabelRun ? '80px' : '0px'" size="medium " :inline="tabsInline"
      :label-position="labelPos">
      <uni-row>
        <uni-col class="uni-col-item" :span="tab.colspan" v-for="(tab,index) in tabRun" :key="index"
          :class="isLastFormItem(tabRun,index) ? '' : 'padding-right'">
          <uni-forms-item class="inline" :label="showLabelRun ? tab.label : ''">
            <template v-slot:label>
              <view v-if="showLabelRun">{{tab.label}}</view>
            </template>
            <uni-datetime-picker class="margin-bottom" v-if="tab._type === 'between'"
              v-model="formModel[tab.list_tab_no].value" type="daterange" @maskClick="maskClick" />
            <view class="form-item">
              <luyj-select-lay v-model="formModel[tab.list_tab_no].value" slabel="text" :name="tab.list_tab_no"
                placeholder="请选择" :options="tab._options" @selectitem="selectChange(tab,$event)"
                v-if="tab._type==='InputSelect'" />
              <uni-easyinput primaryColor="#38c09e" :prefixIcon="tab.prefixIcon||''" v-if="tab._type === 'input'"
                type="text" v-model="formModel[tab.list_tab_no].value" clearable
                :placeholder="tab.placeholder + tab.label" @confirm="onSearch(formModel)" />
              <uni-data-select v-if="tab._type === 'Select' && tab.inputType != '#staff#'"
                v-model="formModel[tab.list_tab_no].value" :clear="true" :localdata="tab._options"
                :placeholder="tab.placeholder" @clear="formModel[tab.list_tab_no].value = ''" @change="selectChange">
              </uni-data-select>
              <uni-data-picker v-else-if="tab.inputType == 'tree'&&tab._options&&tab._options.length>0"
                v-model="formModel[tab.list_tab_no].value" :localdata="tab._options" popup-title="请选择" :clearIcon="true"
                @change="selectChange" :allowSelectBranch="true">
              </uni-data-picker>
              <uni-data-select v-else-if="tab._type === 'Select' && tab.inputType == '#staff#'"
                v-model="formModel[tab.list_tab_no].value" :clear="true" @clear="formModel[tab.list_tab_no].value = ''"
                :localdata="tab._options" :placeholder="tab.placeholder" @change="selectChange"></uni-data-select>
              <uni-data-select v-else-if="tab._type === 'select'" v-model="formModel[tab.list_tab_no].value"
                :clear="true" @clear="formModel[tab.list_tab_no].value = ''" :localdata="tab._options"
                :placeholder="tab.placeholder" @change="selectChange"></uni-data-select>
              <uni-data-select v-else-if=" tab.inputType == 'tree'" v-model="formModel[tab.list_tab_no].value"
                :clear="true" @clear="formModel[tab.list_tab_no].value = ''" :localdata="tab._options"
                :placeholder="tab.placeholder" @change="selectChange"></uni-data-select>
              <uni-data-select class="" v-model="dateRange" :localdata="range"
                @change="dateRangeChange($event,tab.list_tab_no)" v-if="tab._type === 'between'"
                @clear="clearDateRange(tab.list_tab_no)"></uni-data-select>
              <uni-button class="form-item-button g-search" v-if="tab.appendSearchButton" type="primary"
                @click="onSearch(formModel)">查询</uni-button>
            </view>
          </uni-forms-item>
        </uni-col>
      </uni-row>
    </uni-forms>
  </view>
</template>

<script>
  export default {
    name: "retail-filter",
    data() {
      return {
        dateRange: "",
        startDate: '',
        endDate: '',
        range: [{
            value: '今天',
            text: "今天"
          },
          {
            value: '昨天',
            text: "昨天"
          },
          {
            value: '本周',
            text: "本周"
          },
          {
            value: '本月',
            text: "本月"
          }
        ],
        form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
        loading: false,
        inputMoreConfig: {
          value: "",
          options: [{
            'label': '匹配开始',
            'value': 'like]'
          }, {
            'label': '匹配尾部',
            'value': '[like'
          }]
        },
        formModel: {},
        onInputValue: false, // 是否有输入值
      };
    },
    props: {
      tabs: {
        type: Array,
        default: function() {
          return [];
        }
      },

      cols: {
        type: Array,
        default: function() {
          return [];
        }
      },
      srv: {
        type: String,
        default: function() {
          return '';
        }
      },
      labelPos: {
        type: String,
        default: function() {
          return 'left';
        }
      },
      inListType: {
        type: String,
        default: function() {
          return 'listAndDetail';
        }
      }

    },
    computed: {
      tabRun: function() {
        let self = this
        let tabs = self.tabs
        tabs = tabs.map((item, index) => {
          if (!item.orders) {
            item.orders = index + tabs.length
          }
          return item
        })
        tabs = tabs.sort((a, b) => a.orders - b.orders)
        return tabs
      },
      tabsInline: function() {
        let inline = true
        return inline
      },
      showLabelRun: function() {
        let isShow = false
        let tabs = this.tabs
        for (let tab of tabs) {
          if (tab.showLabel) {
            isShow = tab.showLabel
          }
        }
        return isShow
      },
      buildConditionsRun: function() {
        let self = this
        let condsModel = self.formModel
        let relation_Conditions = { // 最外层
          "relation": "AND",
          "data": []
        }
        let tabs = Object.keys(condsModel)
        let colData = {}
        let relation = {
          "relation": "OR",
          "data": []
        }
        if (!tabs) {
          return
        } else {
          for (let i = 0; i < tabs.length; i++) {
            relation.data = []
            colData = {
              "colName": "",
              "ruleType": "",
              "value": ""
            }
            let itemType = condsModel[tabs[i]].inputType || "" // 类型
            let itemColumn = condsModel[tabs[i]].colName // 查询的字段
            let itemValue = condsModel[tabs[i]].value // 用户输入值
            if (itemValue !== null && itemValue !== undefined && itemValue !== "" && itemValue.length >
              0) {
              switch (itemType) {
                case "BetweenDate":
                  for (let col of itemColumn) {
                    colData = {
                      "colName": "",
                      "ruleType": "in",
                      "value": ""
                    }
                    colData.colName = col
                    for (let date in itemValue) {
                      if (date == 0) {
                        colData.ruleType = 'ge'
                        colData.value = itemValue[date] + "  00:00:00"
                      } else if (date == 1) {
                        colData.ruleType = 'le'
                        colData.value = itemValue[date] + "  23:59:59"
                      }
                      relation.data.push(self.deepClone(colData))
                    }
                  }
                  relation.relation = "AND"
                  relation_Conditions.data.push(self.deepClone(relation))
                  break;
                case "Select":
                  for (let col of itemColumn) {
                    colData = {
                      "colName": "",
                      "ruleType": "in",
                      "value": ""
                    }
                    colData.colName = col
                    colData.value = itemValue
                    relation.data.push(self.deepClone(colData))
                    if (colData.value === '_unlimited_') {
                      colData.value = ''
                      colData.ruleType = 'like'
                    }
                  }
                  relation_Conditions.data.push(self.deepClone(relation))
                  break;
                case "String":
                  for (let col of itemColumn) {
                    colData = {
                      "colName": "",
                      "ruleType": "[like]",
                      "value": ""
                    }
                    colData.colName = col
                    colData.value = itemValue
                    relation.data.push(self.deepClone(colData))
                  }

                  relation.relation = "OR"
                  relation_Conditions.data.push(self.deepClone(relation))
                  break;
                case "tree":
                  for (let col of itemColumn) {
                    colData = {
                      "colName": "",
                      "ruleType": "[like]",
                      "value": ""
                    }
                    colData.colName = col
                    colData.value = itemValue
                    relation.data.push(self.deepClone(colData))
                  }
                  relation.relation = "OR"
                  relation_Conditions.data.push(self.deepClone(relation))
                  break;
                default:
                  for (let col of itemColumn) {
                    colData = {
                      "colName": "",
                      "ruleType": "in",
                      "value": ""
                    }
                    colData.colName = col
                    colData.value = itemValue
                    if (colData.value === '_unlimited_') {
                      colData.value = ''
                      colData.ruleType = 'like'
                    }
                    relation.data.push(self.deepClone(colData))
                  }
                  relation_Conditions.data.push(self.deepClone(relation))

                  break;
              }
            }

          }
        }
        return relation_Conditions.data.length > 0 ? relation_Conditions : {}
      }
    },
    created() {
      let self = this
      self.onBuildFormValues()
    },
    methods: {
      clearDateRange(key) {
        console.log('clear');
        this.dateRange = ''
        this.formModel[key].value = ''
        this.$set(this.formModel[key], 'value', '')
      },
      dateRangeChange(e, key) {
        if (!['今天', '昨天', '本周', '本月'].includes(e)) {
          // this.dateRange = '本月'
          // e = '本月'
          return
        }
        // if(!key){
        //   return
        // }
        console.log('dateRangeChange', e, key);
        this.$nextTick(() => {
          let startDate = ''
          let endDate = ''
          if (e == '今天') {
            startDate = this.dayjs().format("YYYY-MM-DD")
            endDate = this.dayjs().format("YYYY-MM-DD")
          } else if (e == '昨天') {
            startDate = this.dayjs().subtract(1, 'day').format("YYYY-MM-DD")
            endDate = this.dayjs().subtract(1, 'day').format("YYYY-MM-DD")
          } else if (e == '本周') {
            startDate = this.dayjs().day(1).format("YYYY-MM-DD")
            endDate = this.dayjs().day(7).format("YYYY-MM-DD")
          } else if (e == '本月') {
            startDate = this.dayjs().startOf('month').format('YYYY-MM-DD')
            endDate = this.dayjs().endOf('month').format('YYYY-MM-DD')
          }
          this.$set(this.formModel[key], 'value', [startDate, endDate])
          // this.$set(this.formModel[key], 'ruleType', 'between')
          console.log(this.formModel);
        })
      },
      selectChange(e, item) {
        if (e?.list_tab_no) {
          if (item?.value) {
            this.$set(this.formModel[e.list_tab_no], 'value', item.value)
          } else {
            this.$set(this.formModel[e.list_tab_no], 'value', null)
          }
        }
      },
      onSearch() {
        this.$emit('on-change', true)
      },
      onBuildFormValues() {
        let self = this
        let tabs = this.tabs
        let model = {}
        tabs.forEach((item, index) => {
          let col = {
            colName: item._colName,
            value: null,
            inputType: item.inputType,
            formType: item._type,
            default: item.default
          }
          item.options = []
          // item.options = self.getTabOptions(item)
          col.colName = item._colName
          col.inputType = item.inputType
          col.formType = item._type
          col.tags = item.more_config ? item.more_config.tags : item.tags || []
          col.options = item.options
          if (item._type === 'input') {
            col.value = item.default
          } else if (item._type === 'select') {
            col.value = ""
          } else if (item._type === 'between' && item.inputType == 'BetweenDate') {
            col.value = []
          }
          model[item.list_tab_no] = col
        })
        // self.$set(self,'condsModel',model)
        self.formModel = model
      },
      getTabSrvCol(tab) {
        let col = tab._colName
        //   tab._colName = col.split(',')
        let cols = tab._colName
        let srvCols = this.cols
        for (let key in cols) {
          for (let c in srvCols) {
            if (cols[key] === srvCols[c].columns) {
              return srvCols[c]
            }
          }
        }
      },
      onChange(e, t) {
        //console.log(e)
      },
      getChecked(e, val) {
        let checked = false
        let checkedItem = e.join(',')
        if (checkedItem.indexOf('_unlimited_') !== -1 && val === '_unlimited_') {
          return true
        } else {
          return false
        }
      },
      onCheckChange(e, item, tabno) {
        //   this.formModel[n].value =
        // 初始不限选项的选中切换
        let self = this

        if (e === true && item.value === '_unlimited_') {
          self.formModel[tabno].value = ['_unlimited_']
        } else if (e === true && item.value !== '_unlimited_') {
          let val = self.formModel[tabno].value
          self.formModel[tabno].value = val.filter((citem, index) => {
            if (citem !== '_unlimited_') {
              return citem
            }
          })

        }
        // console.log('e',e)
      },
      onReset() {
        this.onBuildFormValues()
      },
      buildFkOptionList(query, e) {
        let self = this
        console.log('buildFkOptionList', query, e, self.formModel[e.list_tab_no])
        let cond = []
        self.loading = true
        if (query !== '' && query !== undefined && query !== null) {
          cond = [{
            "colName": e.option_list.key_disp_col,
            "ruleType": "[like]",
            "value": query
          }]
        } else {
          cond = [];
        }
        let options = []
        //   url, service_name, condition, page, order, group, mapcondition,isproc,columns,relationCondition,draft,pageType
        self.select(e.option_list.serviceName, cond, null, null, null, null, null, null, null, null, false).then((
          res) => {
          let resData = res.data.data
          for (let i = 0; i < resData.length; i++) {
            let item = resData[i]
            let opt = {
              value: item[e.option_list.refed_col],
              label: item[e.option_list.key_disp_col]
            }
            options.push(opt)
          }

          // self.formModel[e.list_tab_no]['options'] = options
          // e.options = options
          // self.$set(self.formModel[e.list_tab_no],"options",options)
          console.log("options", options)
          self.formModel[e.list_tab_no].options = options
          self.loading = false
          //  resolve(options)
        })
      },
      getTabOptions(tab) {
        let self = this
        if (tab.hasOwnProperty('_colSrvData')) {
          let scol = tab._colSrvData
          let col = tab._colName
          let options = []
          if (tab._type === 'Select' || tab._type === 'checkbox' || tab._type === 'radio') {
            if (tab.inputType === 'Enum' || tab.inputType === 'Dict' || tab.inputType === 'fk') {
              options = []
              tab['value'] = []
              for (let c = 0; c < col.length; c++) {
                for (let cs = 0; cs < scol.length; cs++) {
                  if (col[c] === scol[cs].columns && scol[cs].col_type === 'Enum') {
                    options = scol[cs].option_list_v2
                    if (tab.showAllTag && options !== undefined) {
                      options.unshift({
                        "label": "不限",
                        "value": "_unlimited_",
                      })
                    }
                    return options
                  } else if (col[c] === scol[cs].columns && scol[cs].col_type === 'Dict') {
                    options = scol[cs].option_list_v2
                    if (tab.showAllTag && options !== undefined) {
                      options.unshift({
                        "label": "不限",
                        "value": "_unlimited_",
                      })
                    }
                    return options
                  }
                  if (col[c] === scol[cs].columns && scol[cs].col_type === 'fk' || scol[cs].col_type ===
                    'Fk') {
                    options = tab['_options']
                    console.log("getTabOptions", tab)
                    return options
                  }
                }
              }
            } else if (tab.inputType === 'BetweenNumber' || tab.inputType === 'Date' || tab.inputType ===
              'DateTime' ||
              tab.inputType === 'String') {
              tab['value'] = []
              options = []
              let opts = tab.more_config.tags
              for (let cs = 0; cs < opts.length; cs++) {
                let obj = {
                  "label": "",
                  "value": "",
                }
                obj.label = opts[cs].tagName
                obj.value = opts[cs].value
                obj.ruleType = opts[cs].ruleType
                obj.checked = opts[cs].default === undefined ? false : opts[cs].default
                options.push(obj)
              }
              if (tab.showAllTag && options !== undefined) {
                options.unshift({
                  "label": "不限",
                  "value": "_unlimited_",
                })
              }
              return options
            } else if (tab.inputType === 'group') {
              let options = []
              self.buildGroupTags(tab).then((res) => {

                let opts = res
                for (let cs = 0; cs < opts.length; cs++) {
                  let obj = {
                    "label": "",
                    "value": "",
                  }
                  obj.label = opts[cs].tagName
                  obj.value = opts[cs].value
                  obj.ruleType = opts[cs].ruleType
                  obj.checked = opts[cs].default === undefined ? false : opts[cs].default
                  options.push(obj)
                }

              })
              self.$set(tab, 'options', options)
              return options
              //console.log('self.buildGroupTags(tab)',self.buildGroupTags(tab))



            }
            //   if(tab.showAllTag && options !== undefined){
            //       options.unshift({
            //         "label":"不限",
            //         "value":"_unlimited_",
            //     })
            //   }
            // // tab.options = options
            // // console.log(options)
            // return options
          }
        } else {
          return []
        }
      },

      buildGroupTags(e) {
        let self = this
        let colName = e._colName[0] || ''
        let group = [{
          colName: colName,
          type: "by"
        }]

        return new Promise((resolve, reject) => {
          let options = []
          self.select(this.srv, [], null, null, group, null).then((res) => {
            let resData = res.data.data
            for (let i = 0; i < resData.length; i++) {
              let item = resData[i]
              let opt = {
                ruleType: "eq",
                tagName: item[colName],
                value: item[colName]
              }
              if (item[colName]) {
                options.push(opt)
              }

            }
            resolve(options)
          })
        })
      },
      buildConditions(e) {
        return this.buildConditionsRun
      },
      formatDateValues(e) {
        let exps = e
        let typeConfig = ['nowDay', 'nowWeek', 'nowMonth', 'nowYear']
        let type = null // nowDay | nowWeek | nowMonth | nowYear
        let increment = 0
        for (let key in typeConfig) {
          if (exps.indexOf(typeConfig[key]) !== -1) {
            type = typeConfig[key]
          }
        }
        let startAndEnd = (exps.indexOf(',') !== -1 ? exps.split(',') : [exps])
        if (startAndEnd[0] == type) {
          increment = (startAndEnd.length == 1 ? 0 : startAndEnd[1])
        } else {
          increment = -startAndEnd[0]
        }
        if (type === 'nowWeek') {
          return DataUtil.getWeekStartAndEnd(increment)
        } else if (type === 'nowDay') {
          return DataUtil.getDayStartAndEnd(increment)
        } else if (type === 'nowMonth') {
          return DataUtil.getMonthStartAndEnd(increment)
        } else if (type === 'nowYear') {
          return dataUtil.getYearStartAndEnd(increment)
        }

      },
      maskClick(e) {
        console.log(e)
      },
      isLastFormItem(tabRun, index) {
        let tabs = tabRun || []
        let i = index
        let row = 0
        let colspan = 0
        let isLast = false
        let list = []
        let listItem = []
        for (let tabi in tabRun) {
          if ((tabRun[tabi].colspan + colspan) == 24) {
            row++
            colspan = 0
            if (tabi == index) {
              isLast = true
            }
          } else {
            colspan = colspan + tabRun[tabi].colspan
          }
        }
        return isLast
      }
    },
    watch: {
      'formModel': {
        deep: true,
        immediate: true,
        handler: function(val, oldVal) {
          let keys = Object.keys(val)
          let onNew = false
          let newNum = 0
          // this.$emit('on-input-value',true)
          // this.$emit('on-change',true)
          for (let i = 0; i < keys.length; i++) {
            //   console.log("更新了",val[keys[i]].value, oldVal[keys[i]].value)
            if (val[keys[i]] && oldVal[keys[i]] && val[keys[i]].hasOwnProperty('value') && oldVal[keys[i]]
              .hasOwnProperty('value') && val[keys[i]].value !== oldVal[keys[i]].value) {
              newNum++
              // this.$emit('on-input-value',true)
              // this.$emit('on-change',true)
              //  console.log("更新了")
            } else if (val[keys[i]] && oldVal[keys[i]] && val[keys[i]].hasOwnProperty('value') && !oldVal[
                keys[i]]
              .hasOwnProperty('value') && val[keys[i]].value !== oldVal[keys[i]].value) {
              // this.$emit('on-input-value',true)
              // this.$emit('on-change',true)
              //  console.log("更新了")
            }
          }
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  .g-search {
    margin-left: 1rem;
  }

  ::v-deep .uni-forms-item__label.no-label {
    display: none;
  }

  .form-item {
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    align-items: center;
    flex-wrap: wrap;
  }

  .margin-bottom {
    margin-bottom: 1rem;
  }

  .uni-col-item {
    margin-bottom: 1rem;
  }

  .between {
    margin-bottom: 1rem;
    background-color: #fff;
    color: #333;
    border: 1px solid #e5e5e5;

    &.active {
      background-color: $retail-color-primary;
      color: #fff;
      border-color: $retail-color-primary;
    }

    .cuIcon-right {
      transform: rotate(90deg);
      margin-left: 1rem;
    }

    &.full-width {
      width: 100%;
    }
  }



  .uni-col.padding-right {
    padding-right: 1.5rem !important;
  }

  ::v-deep .uni-icons.content-clear-icon.uniui-search {
    font-size: 2.4rem !important;
  }

  .filter-list-view {
    padding-bottom: 0;

    &.padding {
      padding-bottom: 0;
    }
  }
</style>
